<template>
  <div >
    <!--<div class="crumbs">
        <el-breadcrumb separator="/">
            <el-breadcrumb-item><i class="el-icon-setting"></i> 系统管理</el-breadcrumb-item>
              <el-breadcrumb-item>{{$route.meta.displayName}}</el-breadcrumb-item>
        </el-breadcrumb>
    </div>-->
  <el-row :gutter="10" type="flex" class="row-bg" justify="space-between">
      <el-col :xs="8" :sm="6" :md="8" :lg="9">
        <div class="grid-content bg-purple">
          <el-input placeholder="请输入内容"   icon="search" v-model="userSearch" :on-icon-click="handleSearchClick">>
            <el-select v-model="search_select" slot="prepend" clearable  placeholder="请选择">
              <el-option label="用户名" value="name"></el-option>
              <el-option label="用户名称" value="userName"></el-option>
            </el-select>
          </el-input>
        </div>
      </el-col>
      <el-col :xs="8" :sm="6" :md="4" :lg="3"><el-button type="primary" @click="handleAddUserClick" icon="el-icon-plus">新增用户</el-button></el-col>
  </el-row>
  <el-row type="flex" class="row-bg" >
    <el-col :span="24">
      <div class="grid-content bg-purple">
        <el-table
            :data="userData"
            max-height="500"
            style="width: 100%">
            <el-table-column
              prop="name"
              label="姓名"
              width="120">
            </el-table-column>
            <el-table-column
              prop="userName"
              label="用户名称"
              min-width="120">
            </el-table-column>
            <el-table-column
              prop="ofRole"
              label="所属角色"
              min-width="100">
            </el-table-column>
            <el-table-column
              prop="sex"
              label="性别"
              min-width="80">
            </el-table-column>
            <el-table-column
              prop="pwdUpdateTime"
              label="密码更改时间"
              min-width="150">
              <template scope="scope">
                  <span style="margin-left: 10px">{{ dataFormatter(scope.row,scope.column) }}</span>
              </template>
            </el-table-column>
            <el-table-column

              label="操作"
              min-width="250">
              <template scope="scope">
                 <el-button @click="handleModifyUserClick(scope.$index,scope.row)"   icon="edit" type="text" size="small">编辑</el-button>


                <el-button @click="handleSignRoleToUserClick(scope.$index,scope.row)"   type="text" size="small">分配角色</el-button>
                <el-button @click="handleResetUserPWDClick(scope.$index,scope.row)"   type="text" size="small">重置密码</el-button>
                <el-button @click="handledeleteUserClick(scope.$index,scope.row)"   type="text" size="small">删除</el-button>

              </template>
            </el-table-column>
            </el-table>
      </div>
    </el-col>
  </el-row>
  <el-row type="flex" justify="end">
      <el-col :span="12">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next"
          :total="total">
        </el-pagination>
    </el-col>
  </el-row>

  <el-dialog :title="dialogTitle"  v-model="dialogUserDataVisible" class="demo-box demo-ruleForm">
      <el-row type="flex" justify="center">
          <el-col :span="24">
            <el-form :model="singleUserDataForm" :rules="userDataValidRules"  ref ="singleUserDataForm">
              <el-form-item prop="name" label-position="right" label="用户名:" :label-width="formLabelWidth"  >
                <el-input v-model="singleUserDataForm.name" auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item prop="userName" label-position="right" label="用户名称:" :label-width="formLabelWidth">
                <el-input v-model="singleUserDataForm.userName" auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item prop= "sex" label-position="right" label="性别" :label-width="formLabelWidth">
                <el-select v-model="singleUserDataForm.sex"  clearable placeholder="请选择性别">
                  <el-option label="男" value="男"></el-option>
                  <el-option label="女" value="女"></el-option>
                </el-select>
              </el-form-item>
            </el-form>

          </el-col>
      </el-row>
      <div slot="footer" v-if="dialogTitle == '新增用户'" class="dialog-footer">
        <el-button @click="handleCancelSubmitForm('singleUserDataForm','dialogUserDataVisible')">取 消</el-button>
        <el-button type="primary" @click="handleAddUserDataActionForm('singleUserDataForm')">确 定</el-button>
      </div>
      <div slot="footer" v-else class="dialog-footer">
        <el-button @click="handleCancelSubmitForm('singleUserDataForm','dialogUserDataVisible')">取 消</el-button>
        <el-button type="primary" @click="handleModifyRoleDataActionForm('singleUserDataForm')">修改</el-button>
      </div>
  </el-dialog>


  <el-dialog title="分配角色"  v-model="dialogSignRoleToUserVisible" class="demo-box demo-ruleForm">
    <el-row type="flex" class="row-bg" justify="center">
      <el-col :span="24">
      <div class="grid-content bg-purple"><h4>已有角色</h4></div>
      <div class="grid-content bg-purple">
          <el-table
              :data="roleData"
              border
              max-height="300"
              style="width: 100%">
              <el-table-column
                @resizable ="resizable"
                prop="name"
                label="角色名"
                min-width="50%">
              </el-table-column>
              <el-table-column
                resizable
                label="操作"
                min-width="50%">
                <template scope="scope">
                  <el-button @click="handleRemoveRoleOfUserClick(scope.$index,scope.row)" type="text" icon="edit" size="small">移除</el-button>
                </template>
              </el-table-column>
              </el-table>
        </div>
      </el-col>
    </el-row>
    <el-row type="flex" justify="end">
        <el-col :span="12">
          <el-pagination
            @size-change="handleRoleDataSizeChange"
            @current-change="handleRoleDataCurrentChange"
            :current-page="roleDataPagination.currentPage"
            :page-sizes="roleDataPagination.pageSizes"
            :page-size="roleDataPagination.pageSize"
            layout="total, sizes, prev, pager, next"
            :total="roleDataPagination.total">
          </el-pagination>
      </el-col>
    </el-row>

    <el-row type="flex" class="row-bg" justify="center">
      <el-col :span="24">
        <div class="grid-content bg-purple"><h5>可选角色</h5></div>
        <div class="grid-content bg-purple">

          <el-table
              :data="availableRole"
              border
              max-height="300"
              style="width: 100%">
              <el-table-column
                @resizable ="resizable"
                prop="name"
                label="角色名"
                min-width="50%">
              </el-table-column>
              <el-table-column
                resizable
                label="操作"
                min-width="50%">
                <template scope="scope">
                  <el-button @click="handleSignAvailableRoleToUserClick(scope.$index,scope.row)" type="text" icon="edit" size="small">上移</el-button>
                </template>
              </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>
    <el-row type="flex" justify="end">
        <el-col :span="12">
          <el-pagination
            @size-change="handleAvailableRoleSizeChange"
            @current-change="handleAvailableRoleCurrentChange"
            :current-page="availableRolePagination.currentPage"
            :page-sizes="availableRolePagination.pageSizes"
            :page-size="availableRolePagination.pageSize"
            layout="total, sizes, prev, pager, next"
            :total="availableRolePagination.total">
          </el-pagination>
      </el-col>
    </el-row>
  </el-dialog>

</div>
</template>


<script>
    import UserService from 'api/security/user'
    import Utils from 'utils/filters'
    export default {
        data: function(){
            return {
              //table
              userData:[],
              currentPage:1,
              pageSizes:[10,20],
              pageSize:10,
              total:0,
              //搜索
              userSearch:'',
              //搜索下拉选择
              search_select:'',
              //用户创建dialog
              dialogUserDataVisible:false,
              dialogTitle:'新增用户',
              //和修改的dialog
              formLabelWidth: '30%',
              //修改用户的data
              singleUserDataForm:{
                id:'',
                name:'',
                userName:'',
                sex:''
              },
              //验证表单规则
              userDataValidRules:{
                name: [{
                  required: true,
                  message: '用户名不能为空',
                  trigger: 'blur'
                }],
                userName: [{
                  required: true,
                  message: '用户名称不能为空',
                  trigger: 'blur'
                }],
                sex: [{
                  required: true,
                  message: '请选择性别',
                  trigger: 'change'
                }],
              },
              //角色分配
              dialogSignRoleToUserVisible:false,
              roleData :[],
              roleDataPagination:{
                currentPage:1,
                pageSizes:[10,20],
                pageSize:10,
                total:0,

              },
              availableRole:[],//可选角色
              availableRolePagination:{
                currentPage:1,
                pageSizes:[10,20],
                pageSize:10,
                total:0,

              }
            }
        },
        methods:{

          handleAddUserDataActionForm(formName){
              this.userDataAction(formName,null,'dialogUserDataVisible');
          },
          handleModifyRoleDataActionForm(formName){
              this.userDataAction(formName,'modify','dialogUserDataVisible');
          },
          userDataAction(formName ,action=null,dialogModeName="dialogUserDataVisible"){
              var self = this;
              this.$refs[formName].validate( (valid)=>{
                  if (valid) {
                      //保存数据
                      var params = {
                          name : self.singleUserDataForm.name,
                          userName:self.singleUserDataForm.userName,
                          sex:self.singleUserDataForm.sex
                      };
                      var msg ="添加成功";
                      if (action !=null){
                          params.id = self.singleUserDataForm.id;
                          msg = "修改成功"
                      }
                      UserService.saveUserData(params).then((response)=>{

                          if (response.data.errorCode == null){
                            self.$message({
                                message: msg,
                                type: "success"
                            });
                            self.$refs[formName].resetFields();
                            //刷新 用户列表
                            self[dialogModeName] = false;
                            self.pageQueryUserData(1,10);
                          }

                      }).catch(err=>{
                          self.$message({
                              message: "操作失败",
                              type: "error"
                          });
                      });
                    //

                  }else{
                    return false ;
                  }
              });
          },

          handleCancelSubmitForm(formName,dialogModeName){
              this.singleUserDataForm ={
                id:'',
                name:'',
                userName:'',
                sex:''
              };
              this[dialogModeName] =false;

          },
          handleAddUserClick(ev){
              this.dialogTitle = '新增用户';
              // this.$refs.singleUserDataForm.resetFields();
              this.singleUserDataForm ={
                id:'',
                name:'',
                userName:'',
                sex:''
              };
              this.dialogUserDataVisible = true;

          },
          handleModifyUserClick(index,row){
            this.$message({
                message: '更改用户信息',
                type: 'info'
            });
            let {id,name,userName ,sex} = row ;
            this.singleUserDataForm = {id,name,userName ,sex};
            this.dialogTitle = '修改用户信息';
            this.dialogUserDataVisible = true;
          },
          handleModifyUserDataActionForm(formName){
              //ti交到后台 修改用户信息
              this.userDataAction(formName);
          },

          //分配角色 按钮点击
          handleSignRoleToUserClick(index,row){
            this.$message({
                message: '角色分配',
                type: 'info'
            });
            this.dialogSignRoleToUserVisible = true;

            //得到已有角色列表

            this.pageQueryRolesByUser({id : row.id});

            //得到 可选角色列表
            this.pageQueryAvailableRolesByUser({id:row.id});



          },
          handleRemoveRoleOfUserClick(index,row){

             var self = this ;
             let params = {
               id:row.ruid
             };

             UserService.delRoleAndUserRelationship(params).then(response => {
               self.$message({
                 message:"移除成功",
                 type:"success"
               });

              self.pageQueryRolesByUser({id : row.userId});
              self.pageQueryAvailableRolesByUser({id:row.userId});
             }).catch(err=>{
               console.log(err);
               self.$message({
                 message:"操作失败",
                 type:"error"
               });
             });
          },

          handleSignAvailableRoleToUserClick(index,row){
            var self = this ;
            var params = {
              userId:row.userId,
              roleId:row.id
            };

            UserService.signRoleToUser(params).then(response =>{
              if (response.data !=null && response.data.errorCode ==null){
                self.$message({
                  message:"分配成功",
                  type:"success"
                });
                self.pageQueryRolesByUser({id : params.userId});
                self.pageQueryAvailableRolesByUser({id:params.userId});
              }else{
                self.$message({
                  message:"操作失败",
                  type:"error"
                });
              }

            }).catch(err =>{
              console.log(err);
              self.$message({
                message:"操作失败",
                type:"error"
              });
            });
          },

          ////已有角色
          pageQueryRolesByUser(params,pageIndex = 1 ,pageSize = 10){
              var self = this ;
              self.roleData = [];
              UserService.pageQueryRolesByUser(params,pageIndex ,pageSize).then(response =>{
                  if (response.data.rows !=null){
                    response.data.rows.forEach(function(item,index,arr){
                      item.userId = params.id ;
                      arr[index] = item;
                    })
                    self.roleData = response.data.rows ;

                    self.roleDataPagination = {
                      currentPage : response.data.pageIndex,
                      pageSize :  response.data.pageSize ,
                      total : response.data.total};
                  }


              }).catch(err =>{
                    console.log(err);
              });
          },
          //可选角色
          pageQueryAvailableRolesByUser(params,pageIndex = 1 ,pageSize = 10){
              var self = this ;
              self.availableRole = [];
              UserService.pageQueryAvailableRolesByUser(params,pageIndex ,pageSize).then(response =>{

                if (response.data.rows !=null){
                  response.data.rows.forEach(function(item,index,arr){
                    item.userId = params.id ;
                    arr[index] = item;
                  });
                  self.availableRole =response.data.rows ;
                  self.availableRolePagination = {
                    currentPage : response.data.pageIndex,
                    pageSize :  response.data.pageSize ,
                    total : response.data.total};
                }

              }).catch(err =>{console.log(err);});

          },
          //重置密码
          handleResetUserPWDClick(index,row){
            var self = this ;
            var confirmInfo = "此操作将重置:"+row.name+"密码,是否继续?";
            self.$confirm(confirmInfo, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                var params = {
                  id : row.id
                };
                UserService.resetUserPwd(params).then(response =>{
                  if (response.data == null || response.data.errorCode ==null){
                    self.$message({
                      type: 'success',
                      message: '重置密码成功!'
                    });

                    //刷新用户列表
                    self.pageQueryUserData(1,10);

                  }else{
                    self.$message({
                      type: 'error',
                      message: '重置密码失败!'
                    });
                  }

                }).catch(err=>{
                  self.$message({
                    type: 'error',
                    message: '重置密码失败!'
                  });
                });
              }).catch(() => {
                self.$message({
                  type: 'info',
                  message: '已取消操作'
                });
              });
          },
          handledeleteUserClick(index,row){
            var self = this ;
            var confirmInfo = "此操作将删除用户:"+row.name+", 是否继续?";
            this.$confirm(confirmInfo, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                if (row.id !=null) {
                  var params = {
                    id : row.id
                  }
                  UserService.delUserData(params).then(response =>{
                    self.$message({
                      type: 'success',
                      message: '删除成功!'
                    });
                    //刷新用户列表
                    self.pageQueryUserData(1,10);
                  }).catch(err=>{
                    self.$message({
                      type: 'error',
                      message: '删除失败!'
                    });
                  });
                }


              }).catch(() => {
                self.$message({
                  type: 'info',
                  message: '已取消删除'
                });
              });

          },
          //日期格式
          dataFormatter(row, column){
              return Utils.formatDate(row.pwdUpdateTime);
          },
          resizable(){
            return false;
          },

          //搜索handle
          handleSearchClick(ev){
            //模糊搜索
            this.$message({
              type:"info",
              message:"搜索"
            })

          },

          //roleData size 变化

          handleRoleDataSizeChange(val){
              this.roleDataPagination.pageSize = val ;
              let userId = this.roleDataPagination.user.id
              this.pageQueryRolesByUser({id:userId},this.currentPage,this.pageSize);
          },

          handleAvailableRoleSizeChange(val){
              this.availableRolePagination.pageSize = val;
              this.pageQueryAvailableRolesByUser({id:userId},this.currentPage,this.pageSize);
          },

          handleSizeChange(val){
            this.pageSize = val;
            this.pageQueryUserData(this.currentPage,this.pageSize);
          },

          handleRoleDataCurrentChange(val){

            this.roleDataPagination.currentPage = val;
            let userId = this.roleDataPagination.user.id;
            this.pageQueryRolesByUser({id:userId},this.currentPage,this.pageSize);
          },
          handleAvailableRoleCurrentChange(val){
            this.availableRolePagination.currentPage = val ;
            let userId = this.roleDataPagination.user.id;
            this.pageQueryAvailableRolesByUser({id:userId},this.currentPage,this.pageSize);
          },
          handleCurrentChange(val){
            this.currentPage = val;
            this.pageQueryUserData(this.currentPage,this.pageSize);
          },
          pageQueryUserData(pageIndex=1,pageSize=10){
            var self = this;
            UserService.pageQueryUserData({},pageIndex,pageSize).then(response =>{
                if (response.data.rows !=null){
                  self.userData =response.data.rows ;
                  self.currentPage = response.data.pageIndex;
                  self.pageSize = response.data.pageSize ;
                  self.total = response.data.total;
                }

            }).catch(err =>{
                console.log(err);
            });
          }
        },
        mounted:function (){
          //UserService
          // this.userData = this.pageQueryUserData(1,10);
          var self = this;
          UserService.pageQueryUserData().then(response =>{
              if (response.data.rows !=null){
                self.userData =response.data.rows ;
                self.currentPage = response.data.pageIndex;
                self.pageSize = response.data.pageSize ;
                self.total = response.data.total;
              }

          }).catch(err =>{
              console.log(err);
          });
        }
    }
</script>

<style scoped>
  .demo-box .el-select, .demo-box .el-input{
    width:60%;
    float: left;

  }
  .el-input .el-select{
    width: 110px;
  }
  .el-row {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .el-col {
    border-radius: 4px;
  }
  .bg-purple-dark {
    background: #99a9bf;
  }
  .bg-purple {
    background: #d3dce6;
  }
  .bg-purple-light {
    background: #e5e9f2;
  }
  .el-col .el-pagination{
    float: right;
  }
  .comicon{
    background-color: #f1f6ff;
    border-right: 2px solid #fff;
    float: left;
    height: 26px;
    margin-left: -1px;
    margin-top: -1px;
    width: 26px;
  }
</style>
